<template>
  <div class="container">
    <div class="app-container">
      <el-button class="btn-add" size="mini" type="primary" @click="hAdd(1)">添加权限</el-button>
      <el-table :data="list" row-key="id">
        <el-table-column label="名称" prop="name" />
        <el-table-column label="标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <!-- 如果当前的 type=2 说明是二级权限，不能有添加功能 -->
            <el-button v-if="row.type !== 2" size="mini" type="text" @click="hAdd(2,row.id)">添加</el-button>
            <el-button size="mini" type="text" @click="hEdit(row.id)">编辑</el-button>
            <template>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="del(row.id)"
              >
                <el-button
                  slot="reference"
                  size="mini"
                  type="text"
                >删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 放置一个弹层 用来编辑新增节点 -->
    <el-dialog
      :title="(isEdit ? '编辑' : '添加') + '新节点'"
      :visible="showDialog"
      @close="btnCancel"
    >
      <!-- 表单 -->
      <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" style="width:90%" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="formData.code" style="width:90%" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input v-model="formData.description" style="width:90%" />
        </el-form-item>
        <el-form-item label="开启">
          <el-switch
            v-model="formData.enVisible"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          <el-button size="small" @click="btnCancel">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getPermission, addPermission, delPermission, getPermissionDetail, updatePermission } from '@/api/permission'
import { arr2tree } from '@/utils/index'

export default {
  name: 'Permission',
  data() {
    return {
      showDialog: false,
      isEdit: false,
      list: [],
      formData: {
        name: '',
        code: '',
        description: '',
        type: '',
        pid: '',
        enVisible: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入权限名称', trigger: 'blur' },
          { min: 2, max: 10, message: '权限名称是2-10位哦', trigger: 'blur' },
          {
            validator: async(rule, value, callback) => {
              // 1.发请求拿到已有权限的名称
              const res = await getPermission()
              // console.log('权限名称已存在')
              // 遍历权限名称，对比是否有重复的
              let data = res.data

              // 如果当前是编辑状态，首先从data 中排出自己
              if (this.isEdit) {
                data = res.data.filter((item) => item.id !== this.formData.id)
              }

              // 判断权限名称是否存在
              if (data.find((item) => item.name === value)) {
                callback(new Error('权限名称[' + value + ']已存在,请更换'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '请输入权限标识', trigger: 'blur' },
          { min: 2, max: 10, message: '权限标识是2-10位哦', trigger: 'blur' },
          { validator: async(rule, value, callback) => {
            const res = await getPermission()
            let data = res.data
            // 如果当前是编辑状态，首先从data 中排出自己
            if (this.isEdit) {
              data = res.data.filter((item) => item.id !== this.formData.id)
            }
            if (data.find((item) => item.code === value)) {
              callback(new Error('权限标识[' + value + ']已存在,请更换'))
            } else {
              callback()
            }
          }, trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.loadPermission()
  },
  methods: {
    async doEdit() {
      await updatePermission(this.formData)
      this.$message.success('恭喜您，编辑成功')
      this.loadPermission()
      this.btnCancel()
    },
    async hEdit(id) {
      this.isEdit = true
      this.showDialog = true
      const res = await getPermissionDetail(id)
      // console.log('数据回显', res)
      this.formData = res.data
    },
    async del(id) {
      await delPermission(id)
      this.loadPermission()
      this.$message.success('恭喜您，删除成功')
    },
    async doAdd() {
      await addPermission(this.formData)
      // console.log(res)
      this.$message.success('恭喜您，添加成功')
      this.loadPermission()
      this.btnCancel()
    },
    async btnOK() {
      this.$refs.perForm.validate((valid) => {
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    btnCancel() {
      this.$refs.perForm.resetFields()
      this.showDialog = false
    },
    hAdd(type, id) {
      this.isEdit = false
      this.showDialog = true
      this.formData.pid = id || 0
      this.formData.type = type
    },
    async loadPermission() {
      const res = await getPermission()
      // console.log('权限', res.data)
      // this.list = res.data
      this.list = arr2tree(res.data, 0)
    }
  }
}
</script>
<style>
.btn-add {
  margin: 10px;
}
</style>
